<template>
  <div>
    <div style="display: flex">
      <div :class="['icon-item', curSelected == icon ? 'selected-item' : '']" v-for="(icon, index) in displayIcons" :key="index" @click="handleIconClick(icon)">
        <span style="" v-if="!icon">无</span>
        <el-icon v-else-if="!svg" :class="icon">
          <component :is="icon" />
        </el-icon>
        <svg-icon v-else :icon-class="icon" />
      </div>
      <el-button type="primary" link @click="openDialog">更多</el-button>
    </div>
    <drag-dialog v-model="visible" width="500px" title="选择图标" @close="closeDialog">
      <div>
        <el-input v-model="filterText" placeholder="搜索图标" style="width: 100%" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <div class="icon-container">
          <div :class="['icon-item', curSelected == icon ? 'selected-item' : '']" v-for="(icon, index) in filterIcons" :key="index" @click="handleIconClick(icon)">
            <span style="" v-if="!icon">无</span>
            <el-icon v-else-if="!svg" :class="icon">
              <component :is="icon" />
            </el-icon>
            <svg-icon v-else :icon-class="icon" />
          </div>
        </div>
      </div>
      <template #footer>
        <dialog-footer @ok="closeDialog" @cancel="closeDialog" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
export default {
  name: 'IconSelector',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    icons: {
      type: Array,
      default: () => []
    },
    svg: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      curSelected: '',
      visible: false,
      filterText: ''
    };
  },
  computed: {
    displayIcons() {
      if (this.icons.length > 15) {
        return this.icons.slice(0, 15);
      } else {
        return this.icons;
      }
    },
    filterIcons() {
      return this.icons.filter((icon) => icon.includes(this.filterText));
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.curSelected = newVal;
      },
      immediate: true
    },
    curSelected(newVal) {
      this.$emit('update:modelValue', newVal);
    }
  },
  methods: {
    handleIconClick(icon) {
      this.curSelected = icon;
    },
    openDialog() {
      this.visible = true;
    },
    closeDialog() {
      this.filterText = '';
      this.visible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.icon-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  height: 300px;
  overflow: auto;
  margin-top: 12px;
}

.icon-item {
  border: 1px solid transparent;
  align-items: center;
  border-radius: 3px;
  color: #525967;
  cursor: pointer;
  display: inline-flex;
  font-size: 14px;
  height: 24px;
  justify-content: center;
  margin: 2px;
  text-align: center;
  width: 24px;
}

.selected-item {
  border-color: #00b899;
}
</style>